package com.boy.aspect;

import com.boy.tool.utils.JwtUtils;
import com.boy.entity.Account;
import com.boy.entity.Log;
import com.boy.entity.Permission;
import com.boy.mapper.AccountMapper;
import com.boy.service.LogService;
import com.boy.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author whd
 * @date 2024/05/23 14:13:45
 */
@Component
@Aspect
@Slf4j
public class AspectConfig {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private LogService logService;

    @Around("@annotation(com.boy.tool.annotate.WhdLog)")
    public Object around(ProceedingJoinPoint pjp) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (attributes != null) {
            request = attributes.getRequest();
        }
        String path = null;
        if (request != null) {
            path = request.getRequestURI();
        }

        String token = null;
        if (request != null) {
            token = request.getHeader("Authorization");
        }
        String id = JwtUtils.getMemberIdByJwtToken(token);
        Account account = accountMapper.selectById(id);
        try {
            Object res = pjp.proceed();
            Permission permission = permissionService.getByPath(path);
            if (permission == null)
                logService.create(new Log("用户进行未知操作", account.getNick(), request.getRemoteAddr(), res.toString()));
            else
                logService.create(new Log(permission.getContext(), account.getNick(), request.getRemoteAddr(), res.toString()));
            return res;
        } catch (Throwable e) {
            log.info("用户执行失败");
            throw new RuntimeException(e);
        } finally {
        }
    }
}
